<template>
  <div class="dashboard-container">
    <!-- 头部欢迎语 -->
    <el-card shadow="never" class="mt-2">
      <el-row class="h-80px">
        <el-col :span="18" :xs="24">
          <div class="flex-x-start">
            <img
              class="wh-80px rounded-full"
              style="width: 80px; height: 80px"
              src="../../assets/logo.png"
            />
            <div class="ml-5">
              <p>{{ greetings }}</p>
              <p class="text-sm text-gray">当前分析数据量：{{ totalComments }} 条评论</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 基础统计分析 -->
    <el-row :gutter="10" class="mt-5">
      <!-- 评论热度分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span style="width: 300px">评论热度分析</span>
              <el-date-picker
                v-model="heatDateRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
                @change="updateHeatChart"
              />
            </div>
          </template>
          <div id="commentHeatChart" style="height: 300px"></div>
        </el-card>
      </el-col>

      <!-- 用户参与度分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span style="width: 300px">用户参与度分析</span>
              <el-select
                v-model="participationType"
                size="small"
                @change="updateParticipationChart"
              >
                <el-option label="按评论数" value="comments" />
                <el-option label="按点赞数" value="likes" />
              </el-select>
            </div>
          </template>
          <div id="userParticipationChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 舆情情感与主题分析 -->
    <el-row :gutter="10" class="mt-5">
      <!-- 情感分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span style="width: 300px">舆情情感分析</span>
              <el-tag type="warning">实时分析</el-tag>
            </div>
          </template>
          <div id="sentimentChart" style="height: 300px"></div>
        </el-card>
      </el-col>

      <!-- 关键词与主题挖掘 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span style="width: 300px">关键词与主题挖掘</span>
              <el-select v-model="keywordType" size="small" @change="updateWordCloud">
                <el-option label="全部评论" value="all" />
                <el-option label="正面评论" value="positive" />
                <el-option label="负面评论" value="negative" />
              </el-select>
            </div>
          </template>
          <div id="wordCloudChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户画像分析 -->
    <el-row :gutter="10" class="mt-5">
      <!-- 用户性别与行为关联 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span style="width: 300px">用户性别与行为关联</span>
              <el-select
                v-model="genderBehaviorType"
                size="small"
                @change="updateGenderBehaviorChart"
              >
                <el-option label="评论数" value="comments" />
                <el-option label="点赞数" value="likes" />
                <el-option label="评论长度" value="length" />
              </el-select>
            </div>
          </template>
          <div id="genderBehaviorChart" style="height: 300px"></div>
        </el-card>
      </el-col>

      <!-- 头像与用户活跃度 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span style="width: 300px">头像与用户活跃度</span>
              <el-tag type="info">数据分析</el-tag>
            </div>
          </template>
          <div id="avatarActivityChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 行业洞察 -->
    <el-row :gutter="10" class="mt-5">
      <!-- 竞品对比分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span style="width: 300px">竞品对比分析</span>
              <el-select v-model="competitorType" size="small" @change="updateCompetitorChart">
                <el-option label="情感对比" value="sentiment" />
                <el-option label="热度对比" value="heat" />
              </el-select>
            </div>
          </template>
          <div id="competitorChart" style="height: 300px"></div>
        </el-card>
      </el-col>

      <!-- 舆论爆发点检测 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span style="width: 300px">舆论爆发点检测</span>
              <el-tag type="danger">实时监控</el-tag>
            </div>
          </template>
          <div id="outbreakChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import * as echarts from "echarts";
import "echarts-wordcloud";
import { useUserStore } from "@/store";

defineOptions({
  name: "PublicOpinionDashboard",
  inheritAttrs: false,
});

const userStore = useUserStore();
const date: Date = new Date();
const greetings = computed(() => {
  const hours = date.getHours();
  if (hours >= 6 && hours < 8) {
    return "早上好，" + userStore.userInfo.username + "！今日舆情分析已准备就绪！";
  } else if (hours >= 8 && hours < 12) {
    return "上午好，" + userStore.userInfo.username + "！最新舆论动态已更新！";
  } else if (hours >= 12 && hours < 18) {
    return "下午好，" + userStore.userInfo.username + "！舆情监控中！";
  } else if (hours >= 18 && hours < 24) {
    return "晚上好，" + userStore.userInfo.username + "！今日舆情总结已生成！";
  } else {
    return "夜深了，" + userStore.userInfo.username + "！夜间舆情监控中！";
  }
});

// 模拟数据总量
const totalComments = ref(12568);

// 图表相关变量
const heatDateRange = ref([new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), new Date()]);
const participationType = ref("comments");
const keywordType = ref("all");
const genderBehaviorType = ref("comments");
const competitorType = ref("sentiment");

// 初始化所有图表
onMounted(() => {
  initCommentHeatChart();
  initUserParticipationChart();
  initSentimentChart();
  initWordCloudChart();
  initGenderBehaviorChart();
  initAvatarActivityChart();
  initCompetitorChart();
  initOutbreakChart();
});

// 1. 评论热度分析图表
const initCommentHeatChart = () => {
  const chart = echarts.init(document.getElementById("commentHeatChart"));

  // 模拟数据 - 按日期统计评论数
  const dateList = [];
  const commentCounts = [];
  const likeCounts = [];

  for (let i = 30; i >= 0; i--) {
    const date = new Date(Date.now() - i * 24 * 60 * 60 * 1000);
    dateList.push(date.toLocaleDateString());
    commentCounts.push(Math.floor(Math.random() * 100) + 50);
    likeCounts.push(Math.floor(Math.random() * 500) + 200);
  }

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      data: ["评论数", "点赞数"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: dateList,
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "评论数",
        type: "line",
        smooth: true,
        data: commentCounts,
        itemStyle: {
          color: "#5470C6",
        },
      },
      {
        name: "点赞数",
        type: "line",
        smooth: true,
        data: likeCounts,
        itemStyle: {
          color: "#EE6666",
        },
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener("resize", function () {
    chart.resize();
  });
};

const updateHeatChart = () => {
  // 实际项目中根据日期范围重新获取数据
  initCommentHeatChart();
};

// 2. 用户参与度分析图表
const initUserParticipationChart = () => {
  const chart = echarts.init(document.getElementById("userParticipationChart"));

  // 模拟数据 - 用户参与度排名
  const userNames = ["用户A", "用户B", "用户C", "用户D", "用户E", "用户F", "用户G", "用户H"];
  const participationData = userNames.map((name) => ({
    name,
    comments: Math.floor(Math.random() * 50) + 10,
    likes: Math.floor(Math.random() * 500) + 100,
  }));

  // 根据当前选择类型排序
  participationData.sort((a, b) => b[participationType.value] - a[participationType.value]);

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
    },
    yAxis: {
      type: "category",
      data: participationData.map((item) => item.name),
    },
    series: [
      {
        name: participationType.value === "comments" ? "评论数" : "点赞数",
        type: "bar",
        data: participationData.map((item) => item[participationType.value]),
        itemStyle: {
          color: "#91CC75",
        },
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener("resize", function () {
    chart.resize();
  });
};

const updateParticipationChart = () => {
  initUserParticipationChart();
};

// 3. 舆情情感分析图表
const initSentimentChart = () => {
  const chart = echarts.init(document.getElementById("sentimentChart"));

  // 模拟数据 - 情感分析结果
  const option = {
    tooltip: {
      trigger: "item",
    },
    legend: {
      top: "5%",
      left: "center",
    },
    series: [
      {
        name: "情感分析",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "18",
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: 6542, name: "正面评价", itemStyle: { color: "#67C23A" } },
          { value: 2340, name: "中性评价", itemStyle: { color: "#909399" } },
          { value: 1686, name: "负面评价", itemStyle: { color: "#F56C6C" } },
        ],
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener("resize", function () {
    chart.resize();
  });
};

// 4. 关键词与主题挖掘图表
const initWordCloudChart = () => {
  const chart = echarts.init(document.getElementById("wordCloudChart"));

  // 模拟数据 - 关键词词云
  const words = [
    { name: "质量", value: 100 },
    { name: "服务", value: 90 },
    { name: "价格", value: 85 },
    { name: "物流", value: 80 },
    { name: "体验", value: 75 },
    { name: "客服", value: 70 },
    { name: "包装", value: 65 },
    { name: "售后", value: 60 },
    { name: "功能", value: 55 },
    { name: "设计", value: 50 },
    { name: "性能", value: 45 },
    { name: "品牌", value: 40 },
    { name: "操作", value: 35 },
    { name: "安装", value: 30 },
    { name: "材质", value: 25 },
  ];

  const option = {
    series: [
      {
        type: "wordCloud",
        shape: "circle",
        left: "center",
        top: "center",
        width: "90%",
        height: "90%",
        right: null,
        bottom: null,
        sizeRange: [12, 40],
        rotationRange: [-90, 90],
        rotationStep: 45,
        gridSize: 8,
        drawOutOfBound: false,
        textStyle: {
          fontFamily: "sans-serif",
          fontWeight: "bold",
          color: function () {
            return (
              "rgb(" +
              [
                Math.round(Math.random() * 160),
                Math.round(Math.random() * 160),
                Math.round(Math.random() * 160),
              ].join(",") +
              ")"
            );
          },
        },
        emphasis: {
          focus: "self",
          textStyle: {
            shadowBlur: 10,
            shadowColor: "#333",
          },
        },
        data: words,
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener("resize", function () {
    chart.resize();
  });
};

const updateWordCloud = () => {
  // 实际项目中根据选择类型重新获取数据
  initWordCloudChart();
};

// 5. 用户性别与行为关联图表
const initGenderBehaviorChart = () => {
  const chart = echarts.init(document.getElementById("genderBehaviorChart"));

  // 模拟数据 - 性别与行为关系
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      data: ["男性", "女性", "未知"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: ["评论数", "点赞数", "评论长度"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "男性",
        type: "bar",
        stack: "total",
        emphasis: {
          focus: "series",
        },
        data: [120, 132, 101],
        itemStyle: {
          color: "#409EFF",
        },
      },
      {
        name: "女性",
        type: "bar",
        stack: "total",
        emphasis: {
          focus: "series",
        },
        data: [220, 182, 191],
        itemStyle: {
          color: "#F56C6C",
        },
      },
      {
        name: "未知",
        type: "bar",
        stack: "total",
        emphasis: {
          focus: "series",
        },
        data: [150, 232, 201],
        itemStyle: {
          color: "#909399",
        },
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener("resize", function () {
    chart.resize();
  });
};

const updateGenderBehaviorChart = () => {
  // 实际项目中根据选择类型重新获取数据
  initGenderBehaviorChart();
};

// 6. 头像与用户活跃度图表
const initAvatarActivityChart = () => {
  const chart = echarts.init(document.getElementById("avatarActivityChart"));

  // 模拟数据 - 头像与活跃度关系
  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      left: 10,
      data: ["有头像用户", "无头像用户"],
    },
    series: [
      {
        name: "活跃度分布",
        type: "pie",
        radius: ["50%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "18",
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: 735, name: "有头像用户" },
          { value: 265, name: "无头像用户" },
        ],
        itemStyle: {
          color: function (params) {
            const colorList = ["#67C23A", "#E6A23C"];
            return colorList[params.dataIndex];
          },
        },
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener("resize", function () {
    chart.resize();
  });
};

// 7. 竞品对比分析图表
const initCompetitorChart = () => {
  const chart = echarts.init(document.getElementById("competitorChart"));

  // 模拟数据 - 竞品对比
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      data: ["品牌A", "品牌B", "品牌C", "品牌D"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
    },
    yAxis: {
      type: "category",
      data: ["正面评价", "中性评价", "负面评价"],
    },
    series: [
      {
        name: "品牌A",
        type: "bar",
        stack: "total",
        label: {
          show: true,
        },
        emphasis: {
          focus: "series",
        },
        data: [320, 302, 301],
        itemStyle: {
          color: "#5470C6",
        },
      },
      {
        name: "品牌B",
        type: "bar",
        stack: "total",
        label: {
          show: true,
        },
        emphasis: {
          focus: "series",
        },
        data: [120, 132, 101],
        itemStyle: {
          color: "#91CC75",
        },
      },
      {
        name: "品牌C",
        type: "bar",
        stack: "total",
        label: {
          show: true,
        },
        emphasis: {
          focus: "series",
        },
        data: [220, 182, 191],
        itemStyle: {
          color: "#FAC858",
        },
      },
      {
        name: "品牌D",
        type: "bar",
        stack: "total",
        label: {
          show: true,
        },
        emphasis: {
          focus: "series",
        },
        data: [150, 212, 201],
        itemStyle: {
          color: "#EE6666",
        },
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener("resize", function () {
    chart.resize();
  });
};

const updateCompetitorChart = () => {
  // 实际项目中根据选择类型重新获取数据
  initCompetitorChart();
};

// 8. 舆论爆发点检测图表
const initOutbreakChart = () => {
  const chart = echarts.init(document.getElementById("outbreakChart"));

  // 模拟数据 - 舆论爆发点
  const hours = [];
  const commentCounts = [];
  const alertThreshold = [];

  for (let i = 0; i < 24; i++) {
    hours.push(i + ":00");
    const baseCount = Math.floor(Math.random() * 20);
    // 随机生成一个爆发点
    const isOutbreak = Math.random() > 0.9;
    commentCounts.push(isOutbreak ? baseCount + 80 : baseCount + 10);
    alertThreshold.push(50); // 预警阈值
  }

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        data: hours,
      },
    ],
    yAxis: [
      {
        type: "value",
      },
    ],
    series: [
      {
        name: "评论量",
        type: "line",
        stack: "Total",
        areaStyle: {},
        emphasis: {
          focus: "series",
        },
        data: commentCounts,
        itemStyle: {
          color: "#FF0000",
        },
        markPoint: {
          data: [
            { type: "max", name: "最大值" },
            { type: "min", name: "最小值" },
          ],
        },
        markLine: {
          data: [{ type: "average", name: "平均值" }],
        },
      },
      {
        name: "预警阈值",
        type: "line",
        stack: "Total",
        data: alertThreshold,
        itemStyle: {
          color: "#000000",
        },
        lineStyle: {
          type: "dashed",
        },
        markArea: {
          itemStyle: {
            color: "rgba(255, 0, 0, 0.1)",
          },
          data: [
            [
              {
                yAxis: 50,
              },
              {
                yAxis: 100,
              },
            ],
          ],
        },
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener("resize", function () {
    chart.resize();
  });
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;
}

.text-gray {
  color: var(--el-text-color-secondary);
}

.mt-2 {
  margin-top: 0.5rem;
}

.mt-5 {
  margin-top: 1.25rem;
}

.ml-5 {
  margin-left: 1.25rem;
}

.wh-80px {
  width: 80px;
  height: 80px;
}

.rounded-full {
  border-radius: 9999px;
}

.flex-x-start {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.flex-x-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.flex-y-center {
  display: flex;
  align-items: center;
}

.h-80px {
  height: 80px;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.text-lg {
  font-size: 1.125rem;
  line-height: 1.75rem;
}

.text-xs {
  font-size: 0.75rem;
  line-height: 1rem;
}
</style>
